package com.eqdd.yiqidian.ui.chat;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.ClipboardManager;
import android.text.Selection;
import android.text.Spannable;
import android.view.View;
import android.widget.TextView;

import com.eqdd.yiqidian.ConversitionActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.base.DemoContext;
import com.eqdd.yiqidian.bean.BaseBean;
import com.eqdd.yiqidian.bean.rebuild.GroupMemberListResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.rongyun.MingpianMessage;
import com.eqdd.yiqidian.ui.MainActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.ui.mine.renwu.CreateRenwuActivity;
import com.eqdd.yiqidian.ui.mine.shenqing.CreateMemoActivity;
import com.eqdd.yiqidian.ui.mine.wo.CollectionActivity;
import com.eqdd.yiqidian.ui.share.ShareEnterActivity;
import com.eqdd.yiqidian.ui.tongxunlu.TeamCheatInfoActivity;
import com.eqdd.yiqidian.utils.FileProviderUtil;
import com.eqdd.yiqidian.utils.FileUtil;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.GsonUtils;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.utils.ShareUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.rong.callkit.RongCallKit;
import io.rong.common.RLog;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imkit.manager.AudioPlayManager;
import io.rong.imkit.manager.SendImageManager;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imkit.utilities.OptionsPopupDialog;
import io.rong.imlib.MessageTag;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.TypingMessage.TypingStatus;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import io.rong.message.FileMessage;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;
import rx.android.schedulers.AndroidSchedulers;

import static io.rong.imkit.utils.SystemUtils.getCurProcessName;


/**
 * Created by vzhihao on 2017/2/25.
 */
public class NewConversationActivity extends BaseActivity {
    private static final String BEIWANGLU = "转入备忘录";
    private static final String RENWU = "转入任务";
    private static final String COPY = "复制";
    private static final String DELIVER = "发送给朋友/同事";
    private static final String COLLECTION = "收藏";
    private static final String DELETE = "删除";
    private static final String RECALL = "撤回消息";
    private static final String TITLE = "易企点";
    public static final int SET_TEXT_TYPING_TITLE = 1;
    public static final int SET_VOICE_TYPING_TITLE = 2;
    public static final int SET_TARGETID_TITLE = 3;

    private String mTargetId;

    /**
     * 刚刚创建完讨论组后获得讨论组的id 为targetIds，需要根据 为targetIds 获取 targetId
     */
    private String mTargetIds;

    /**
     * 会话类型
     */
    private Conversation.ConversationType mConversationType;
    private String title;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SET_TEXT_TYPING_TITLE:
                    dataBinding.includeTitle.tvTitle.setText("对方正在输入...");
                    break;
                case SET_VOICE_TYPING_TITLE:
                    dataBinding.includeTitle.tvTitle.setText("对方正在说话...");
                    break;
                case SET_TARGETID_TITLE:
                    dataBinding.includeTitle.tvTitle.setText(title);
                    break;
            }
        }
    };
    private ConversationFragment fragment;
    private ConversitionActivityCustom dataBinding;
    private String source;
    private String textContent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        super.onCreate(savedInstanceState);

    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_conversition);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setView() {
        Intent intent = getIntent();

        getIntentData(intent);

        isReconnect(intent);
        RongIMClient.setTypingStatusListener((type, targetId, typingStatusSet) -> {
            //当输入状态的会话类型和targetID与当前会话一致时，才需要显示
            if (type.equals(mConversationType) && targetId.equals(mTargetId)) {
                //count表示当前会话中正在输入的用户数量，目前只支持单聊，所以判断大于0就可以给予显示了
                int count = typingStatusSet.size();
                if (count > 0) {
                    Iterator iterator = typingStatusSet.iterator();
                    TypingStatus status = (TypingStatus) iterator.next();
                    String objectName = status.getTypingContentType();

                    MessageTag textTag = TextMessage.class.getAnnotation(MessageTag.class);
                    MessageTag voiceTag = VoiceMessage.class.getAnnotation(MessageTag.class);
                    //匹配对方正在输入的是文本消息还是语音消息
                    if (objectName.equals(textTag.value())) {
                        //显示“对方正在输入”
                        mHandler.sendEmptyMessage(SET_TEXT_TYPING_TITLE);
                    } else if (objectName.equals(voiceTag.value())) {
                        //显示"对方正在讲话"
                        mHandler.sendEmptyMessage(SET_VOICE_TYPING_TITLE);
                    }
                } else {
                    //当前会话没有用户正在输入，标题栏仍显示原来标题
                    mHandler.sendEmptyMessage(SET_TARGETID_TITLE);
                }
            }
        });
        RongIM.setConversationBehaviorListener(new RongIM.ConversationBehaviorListener() {
            @Override
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                Intent intent1 = new Intent(NewConversationActivity.this, UserCardActivity.class);
                intent1.putExtra(Config.GUID, userInfo.getUserId());
                startActivity(intent1);
                return true;
            }

            @Override
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                return false;
            }

            @Override
            public boolean onMessageClick(Context context, View view, io.rong.imlib.model.Message message) {
//                if (message.getContent() instanceof FileMessage) {
//                    if (((FileMessage) message.getContent()).getType().equals("avi")||((FileMessage) message.getContent()).getType().equals("mp4")) {
//                        Intent intent = new Intent(ConversationActivity.this, VideoPlayActivity.class);
//                        Bundle bundle = new Bundle();
//                        if (((FileMessage) message.getContent()).getLocalPath()!=null){
//                            bundle.putString(Config.VIDEO_URL, String.valueOf(((FileMessage) message.getContent()).getLocalPath()));
//                            intent.putExtras(bundle);
//                            startActivity(intent);
//                        }else {
//                            bundle.putString(Config.VIDEO_URL, String.valueOf(((FileMessage) message.getContent()).getMediaUrl()));
//                            intent.putExtras(bundle);
//
//                            startActivity(intent);
//                        }
//                        return true;
//                    }
//                }
                return false;
            }

            @Override
            public boolean onMessageLinkClick(Context context, String s) {
                return false;
            }

            @Override
            public boolean onMessageLongClick(Context context, View view, io.rong.imlib.model.Message message) {

                showLongClickDialog(context, view, message);
                return true;
            }
        });
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    private void showLongClickDialog(Context context, View view, io.rong.imlib.model.Message message) {
        if (message.getContent() instanceof TextMessage) {//文字
            dealTextMeaasge(view, message);
        } else if (message.getContent() instanceof ImageMessage) {//图片
            dealImgMessage(view, message);
        } else if (message.getContent() instanceof FileMessage) {//文件
            dealFileMessage(view, message);
        } else if (message.getContent() instanceof VoiceMessage) {//语音
            dealVoiceMessage(view, message);
        } else if (message.getContent() instanceof LocationMessage) {//地图
            dealLocationMessage(view, message);
        } else if (message.getContent() instanceof MingpianMessage) {//名片
            dealMingpianMessage(view, message);
        } else {
            dealOther(view, message);
        }
    }

    private void dealOther(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELETE, RECALL};
        } else {
            items = new String[]{DELETE};
        }
        showLongPressDialog(view, message, items);
    }

    private void dealMingpianMessage(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELIVER, DELETE, RECALL};
        } else {
            items = new String[]{DELIVER, DELETE};
        }
        showLongPressDialog(view, message, items);
    }

    private void dealLocationMessage(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELIVER, COLLECTION, DELETE, RECALL};
        } else {
            items = new String[]{DELIVER, COLLECTION, DELETE};
        }
        showLongPressDialog(view, message, items);
    }

    private void dealVoiceMessage(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELETE, RECALL};
        } else {
            items = new String[]{DELETE};
        }
        showLongPressDialog(view, message, items);
    }

    private void dealFileMessage(View view, io.rong.imlib.model.Message message) {
        long deltaTime = RongIM.getInstance().getDeltaTime();
        long normalTime = System.currentTimeMillis() - deltaTime;
        boolean enableMessageRecall = false;
        int messageRecallInterval = -1;

        String realPathFromUri = FileProviderUtil.getRealPathFromUri(this, ((FileMessage) message.getContent()).getFileUrl());
        String realFilePath = FileProviderUtil.getRealFilePath(this, ((FileMessage) message.getContent()).getFileUrl());
        try {
            enableMessageRecall = RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_message_recall);
            messageRecallInterval = RongContext.getInstance().getResources().getInteger(io.rong.imkit.R.integer.rc_message_recall_interval);
        } catch (Resources.NotFoundException var13) {
            RLog.e("FileMessageItemProvider", "rc_message_recall_interval not configure in rc_config.xml");
            var13.printStackTrace();
        }
        if (!message.getSentStatus().equals(io.rong.imlib.model.Message.SentStatus.SENDING)) {
            String[] items;
            if (((FileMessage) message.getContent()).getLocalPath() == null) {
                items = new String[]{DELETE};

            } else if (message.getSentStatus().equals(io.rong.imlib.model.Message.SentStatus.SENT) && enableMessageRecall && normalTime - message.getSentTime() <= (long) (messageRecallInterval * 1000) && message.getSenderUserId().equals(RongIM.getInstance().getCurrentUserId()) && !message.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.APP_PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.SYSTEM) && !message.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
                items = new String[]{DELIVER, DELETE, RECALL};
            } else {
                items = new String[]{DELIVER, DELETE};
            }

            showLongPressDialog(view, message, items);
        }
    }

    private void dealImgMessage(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELIVER, DELETE, RECALL};
        } else {
            items = new String[]{DELIVER, DELETE};
        }
        String path = ((ImageMessage) message.getContent()).getLocalUri().getPath();
        showLongPressDialog(view, message, items);

    }

    private void dealTextMeaasge(View view, io.rong.imlib.model.Message message) {
        if (view instanceof TextView) {
            CharSequence items = ((TextView) view).getText();
            if (items != null && items instanceof Spannable) {
                Selection.removeSelection((Spannable) items);
            }
        }
        if (message.getContent() instanceof TextMessage) {
            textContent = ((TextMessage) message.getContent()).getContent();
        }
        String[] items1;
        if (isCancel(message)) {
            items1 = new String[]{BEIWANGLU, RENWU, COPY, DELIVER, COLLECTION, DELETE, RECALL};
        } else {
            items1 = new String[]{BEIWANGLU, RENWU, COPY, DELIVER, COLLECTION, DELETE,};
        }

        showLongPressDialog(view, message, items1);
    }

    private void showLongPressDialog(View view, io.rong.imlib.model.Message message, String[] items1) {
        OptionsPopupDialog.newInstance(view.getContext(), items1).setOptionsPopupDialogListener(which -> {
            Bundle bundle = new Bundle();
            switch (items1[which]) {
                case BEIWANGLU:
                    if (message.getContent() instanceof TextMessage) {
                        bundle.putString(Config.CONTENT, textContent);
                        startActivity(CreateMemoActivity.class, bundle);
                    }
                    break;
                case RENWU:
                    if (message.getContent() instanceof TextMessage) {
                        bundle.putString(Config.CONTENT, textContent);
                        startActivity(CreateRenwuActivity.class, bundle);
                    }
                    break;
                case COPY:
                    if (message.getContent() instanceof TextMessage) {
                        ClipboardManager clipboard = (ClipboardManager) view.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                        clipboard.setText(textContent);
                    }
                    break;
                case DELIVER:
                    AppConstent.messageContent = message.getContent();
                    if (message.getContent() instanceof TextMessage) {
                        ShareUtil.shareMsgText(NewConversationActivity.this, "易企点", "分享",
                                textContent);
                    } else {
                        startActivity(ShareEnterActivity.class);
                    }
                    break;
                case COLLECTION:
                    if (message.getContent() instanceof TextMessage) {
                        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.ADD_COLLECTION)
                                .params("owner", AppConstent.user.getGuid())
                                .params("type", 2)
                                .params("title", "我的收藏")
                                .params("tel", AppConstent.user.getUname())
                                .params("source", source)
                                .params("sourceOwner", message.getContent().getUserInfo().getUserId())
                                .params("ccontent", textContent)
                                .execute(new DialogCallBack<HttpResult>(NewConversationActivity.this) {
                                    @Override
                                    public void onSuccess(Response<HttpResult> response) {
                                        HttpResult httpResult = response.body();
                                        ToastUtil.showShort(httpResult.getMsg());
                                        if (httpResult.getStatus() == 200) {
                                        }
                                    }
                                });
                    } else if (message.getContent() instanceof LocationMessage) {
                        String position = ((LocationMessage) message.getContent()).getLat() + "," + ((LocationMessage) message.getContent()).getLng();
                        String map = ((LocationMessage) message.getContent()).getPoi();
                        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.ADD_COLLECTION)
                                .params("owner", AppConstent.user.getGuid())
                                .params("type", 6)
                                .params("position", position)
                                .params("ccontent", map)
                                .params("source", "我的收藏")
                                .params("sourceOwner", AppConstent.user.getGuid())
                                .execute(new DialogCallBack<HttpResult>(NewConversationActivity.this) {
                                    @Override
                                    public void onSuccess(Response<HttpResult> response) {
                                        HttpResult httpResult = response.body();
                                        ToastUtil.showShort(httpResult.getMsg());
                                        if (httpResult.getStatus() == 200) {

                                        }
                                    }
                                });
                    }
                    break;
                case DELETE:
                    if (message.getContent() instanceof VoiceMessage) {
                        AudioPlayManager.getInstance().stopPlay();
                    } else if (message.getContent() instanceof FileMessage) {
                        RongIM.getInstance().cancelSendMediaMessage(message, null);
                    } else if (message.getContent() instanceof ImageMessage) {
                        SendImageManager.getInstance().cancelSendingImage(message.getConversationType(), message.getTargetId(), message.getMessageId());

                    }
                    RongIM.getInstance().deleteMessages(new int[]{message.getMessageId()}, null);
                    break;
                case RECALL:
                    RongIM.getInstance().recallMessage(message, getPushContent(view.getContext(), message));
                    break;

            }
        }).show();
    }

    @NonNull
    private boolean isCancel(io.rong.imlib.model.Message message) {
        long deltaTime = RongIM.getInstance().getDeltaTime();
        long normalTime = System.currentTimeMillis() - deltaTime;
        boolean enableMessageRecall = false;
        int messageRecallInterval = -1;
        boolean hasSent = !message.getSentStatus().equals(io.rong.imlib.model.Message.SentStatus.SENDING) && !message.getSentStatus().equals(io.rong.imlib.model.Message.SentStatus.FAILED);

        try {
            enableMessageRecall = RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_message_recall);
            messageRecallInterval = RongContext.getInstance().getResources().getInteger(io.rong.imkit.R.integer.rc_message_recall_interval);
        } catch (Resources.NotFoundException var15) {
            RLog.e("TextMessageItemProvider", "rc_message_recall_interval not configure in rc_config.xml");
            var15.printStackTrace();
        }

        return (hasSent && enableMessageRecall && normalTime - message.getSentTime() <= (long) (messageRecallInterval * 1000) && message.getSenderUserId().equals(RongIM.getInstance().getCurrentUserId()) && !message.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.APP_PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.SYSTEM) && !message.getConversationType().equals(Conversation.ConversationType.CHATROOM));
    }

    public String getPushContent(Context context, io.rong.imlib.model.Message message) {
        String userName = "";
        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(message.getSenderUserId());
        if (userInfo != null) {
            userName = userInfo.getName();
        }

        return context.getString(io.rong.imkit.R.string.rc_user_recalled_message, userName);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }

    /**
     * 展示如何从 Intent 中得到 融云会话页面传递的 Uri
     */
    private void getIntentData(Intent intent) {

        mTargetId = intent.getData().getQueryParameter("targetId");
        mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
        title = getIntent().getData().getQueryParameter("title");
        source = mConversationType == Conversation.ConversationType.PRIVATE ? "私聊-" + title : "群组-" + title;
        initTopTitleBar(View.VISIBLE, title);
        enterFragment(mConversationType, mTargetId);
        if (mConversationType == Conversation.ConversationType.GROUP) {
            initTopRightImage(R.mipmap.talk_qun, v -> {
                Bundle bundle = new Bundle();
                bundle.putString("groupid", mTargetId);
                bundle.putString("groupname", title);
                startActivity(TeamCheatInfoActivity.class, bundle);
            });
            RongCallKit.setGroupMemberProvider((groupId, result) -> {
                new HttpPresneter.Builder(HttpConfig.GROUP_USER_LIST, String.class, null)
                        .Params("groupid", mTargetId)
                        .setOnHttpListener(new HttpPresneter.OnHttpListener() {
                            @Override
                            public void onError(Throwable e) {
                                System.out.println(e.toString());
                            }

                            @Override
                            public void onNext(Object o) {
                                BaseBean<GroupMemberListResultBean> friendBeanBaseBean = GsonUtils.changeGsonToBaseBean((String) o, GroupMemberListResultBean.class);
                                ArrayList<String> userInfos = new ArrayList<>();
                                if (friendBeanBaseBean.getItems() != null) {
                                    for (GroupMemberListResultBean friendBean : friendBeanBaseBean.getItems()) {
                                        UserInfo userInfo = new UserInfo(friendBean.getGuid(), friendBean.getUpname(), Uri.parse(friendBean.getIphoto()));
                                        userInfos.add(userInfo.getUserId());
                                        RongIM.getInstance().refreshUserInfoCache(userInfo);
                                        RongUserInfoManager.getInstance().setUserInfo(userInfo);

                                    }
                                    result.onGotMemberList(userInfos);
                                }
                            }
                        })
                        .build()
                        .post();
                return null;
            });
            RongIM.getInstance().setGroupMembersProvider((s, iGroupMemberCallback) -> new HttpPresneter.Builder(HttpConfig.GROUP_USER_LIST, String.class, null)
                    .Params("groupid", mTargetId)
                    .setOnHttpListener(new HttpPresneter.OnHttpListener() {
                        @Override
                        public void onError(Throwable e) {
                            System.out.println(e.toString());
                        }

                        @Override
                        public void onNext(Object o) {
                            BaseBean<GroupMemberListResultBean> friendBeanBaseBean = GsonUtils.changeGsonToBaseBean((String) o, GroupMemberListResultBean.class);
                            ArrayList<UserInfo> userInfos = new ArrayList<>();
                            if (friendBeanBaseBean.getItems() != null) {
                                for (GroupMemberListResultBean friendBean : friendBeanBaseBean.getItems()) {
                                    UserInfo userInfo = new UserInfo(friendBean.getGuid(), friendBean.getUpname(), Uri.parse(friendBean.getIphoto()));
                                    userInfos.add(userInfo);
                                    RongIM.getInstance().refreshUserInfoCache(userInfo);
                                    RongUserInfoManager.getInstance().setUserInfo(userInfo);

                                }
                                iGroupMemberCallback.onGetGroupMembersResult(userInfos);
                            }
                        }
                    })
                    .build()
                    .post());
        } else {
            initTopRightImage(R.mipmap.talk_person, v -> {
                Bundle bundle = new Bundle();
                bundle.putString(Config.GUID, mTargetId);
                startActivity(UserCardActivity.class, bundle);
            });
        }

    }


    /**
     * 加载会话页面 ConversationFragment
     *
     * @param mConversationType
     * @param mTargetId
     */

    private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

        fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);

        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", mTargetId).build();
        fragment.setUri(uri);
    }


    /**
     * 判断消息是否是 push 消息
     */
    private void isReconnect(Intent intent) {


        String token = null;

        if (DemoContext.getInstance() != null) {
            token = SPUtil.getToken(GreenDaoUtil.getUser().getUname());
        }

        //push或通知过来
        if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong")) {

            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("push") != null
                    && intent.getData().getQueryParameter("push").equals("true")) {

                reconnect(token);
            } else {
                //程序切到后台，收到消息后点击进入,会执行这里
                if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null) {

                    reconnect(token);
                } else {
                    enterFragment(mConversationType, mTargetId);
                }
            }
        }
    }


    /**
     * 重连
     *
     * @param token
     */
    private void reconnect(String token) {

        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {

                    enterFragment(mConversationType, mTargetId);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }
}
